#问题一，练习作用域之间的转换
total = 0
def sum(a, b):
    total = a + b
    print("函数内是局部变量：", total)
    return total
print(sum(5, 10))
print("函数外是全局变量：", total)

total1 = 1
def func():
    global total1
    print(total1)
    total1 = 2
    print(total1)
print(func())
print(total1)

def a():
    total = 1
    def b():
        nonlocal total
        total = 3
        print(total)
        return b
    b()
    print(total)
a()

#问题二，实现一个装饰器，用来输出函数的执行时间
import time
def clock_deco(func):
    def wrap(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} 执行时长为：{format(end_time - start_time, '.2f')}s")
        return result
    return wrap

@clock_deco
def cool(a, b):
    num = 0
    while True:
        if num >= a ** b:
            break
        num += 1

cool(5, 10)

#问题三，使用装饰器来为斐波那契函数增加缓存
a = {}
def cache_deco(func):
    global a
    def wrap(n):
        if n not in a:
            a[n] = func(n)
        return a[n]
    return wrap

@ cache_deco
def fib(n):
    if n < 2:
        return n
    else:
        return fib(n - 2) + fib(n - 1)

print(fib(10))
print(a)